<template>
    <v-container>
        <form>
            <v-text-field color="primary" v-model="wordBo.word" label="单词" />
            <v-autocomplete color="primary" clearable chips label="选择标签" item-title="name" item-value="id" :items="labelList"
                v-model="wordBo.labelList" multiple variant="outlined"/>
            <v-autocomplete color="primary" v-model="wordBo.langId" clearable label="选择语种" item-title="lang" item-value="langId" :items="langList"
                variant="outlined" chips/>
            <v-autocomplete color="primary" v-model="wordBo.bookList" clearable label="添加到词典" multiple item-title="title" item-value="id"
                :items="bookList" variant="outlined" chips/>
            <v-file-input color="primary" accept="image/png, image/jpeg, image/bmp" @update:model-value="uploadWordImage" show-size clearable
                label="单词图片"/>
            <v-img :src="wordBo.image" width="100" height="100" v-if="wordBo.image!=null" />
            <v-textarea color="primary" v-model="wordBo.etymologyPlain" label="词源" />
            <v-textarea color="primary" v-model="wordBo.remark" label="备注" />
            <v-sheet>
                <v-expansion-panels multiple>
                    <v-expansion-panel title="源语种释义">
                        <v-expansion-panel-text>
                            <v-divider />
                            <strong>缺省</strong>
                            <v-text-field color="primary" v-model="originalMeaningsDefault.symbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeaningsDefault.explain" label="基本释义" />

                            <v-divider />
                            <strong>名词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.nounSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.noun" label="名词" />

                            <v-divider />
                            <strong>动词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.verbSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.verb" label="及物和不及物动词" />

                            <v-divider />
                            <strong>形容词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.adjSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.adj" label="形容词" />

                            <v-divider />
                            <strong>副词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.advSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.adv" label="副词" />

                            <v-divider />
                            <strong>介词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.prepSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.prep" label="介词" />

                            <v-divider />
                            <strong>代词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.pronSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.pron" label="代词" />

                            <v-divider />
                            <strong>助词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.auxSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.aux" label="助词" />

                            <v-divider />
                            <strong>数词</strong>
                            <v-text-field color="primary" v-model="originalMeanings.numSymbol" label="发音" />
                            <v-textarea color="primary" v-model="originalMeanings.num" label="助词" />
                        </v-expansion-panel-text>
                    </v-expansion-panel>
                </v-expansion-panels>
            </v-sheet>

            <br>

            <v-sheet>
                <v-expansion-panels multiple>
                    <v-expansion-panel title="翻译释义">
                        <v-expansion-panel-text>
                            <v-sheet v-for="(translatedMeanings, index) in translatedMeaningsList" v-bind:key="index">
                                <!-- <v-text-field v-model="translatedMeanings.type" label="词性" /> -->
                                <v-select v-model="translatedMeanings.type" clearable label="词性" :items="classList"
                                    variant="outlined" />
                                <v-textarea color="primary" v-model="translatedMeanings.meaning" label="翻译" />
                                <v-textarea color="primary" v-model="translatedMeanings.remark" label="备注" />
                                <!-- <v-file-input clearable label="音频文件"></v-file-input> -->
                                <v-divider />
                                <br>
                            </v-sheet>
                            <v-btn color="primary" @click="addtranslatedMeanings">新增</v-btn>
                        </v-expansion-panel-text>
                    </v-expansion-panel>
                </v-expansion-panels>
            </v-sheet>

            <br>

            <v-sheet>
                <v-expansion-panels multiple>
                    <v-expansion-panel title="发音">
                        <v-expansion-panel-text>
                            <v-sheet v-for="(pronunciation, index) in pronunciationList" v-bind:key="index">
                                <v-text-field color="primary" v-model="pronunciation.symbol" label="音标" />
                                <v-text-field color="primary" v-model="pronunciation.region" label="使用地区" />
                                <v-text-field color="primary" v-model="pronunciation.remark" label="备注" />
                                <v-file-input color="primary" label="音频文件" @update:model-value="uploadPronunciationAudio($event,index)" 
                                    show-size clearable accept="audio/mp3,audio/wav,audio/ogg"/>
                                <audio :src="pronunciation.resource" controls v-if="pronunciation.resource!=null" />
                                <v-divider />
                                <br>
                            </v-sheet>
                            <v-btn color="primary" @click="addPronunciationList">新增</v-btn>
                        </v-expansion-panel-text>
                    </v-expansion-panel>
                </v-expansion-panels>
            </v-sheet>

            <br>

            <v-sheet>
                <v-expansion-panels multiple>
                    <v-expansion-panel title="例句" value="sentence">
                        <v-expansion-panel-text>
                            <v-sheet v-for="(sentence, index) in sentenceList" v-bind:key="index">
                                <v-textarea color="primary" v-model="sentence.self" label="句子" />
                                <v-textarea color="primary" v-model="sentence.meaning" label="翻译" />
                                <v-textarea color="primary" v-model="sentence.remark" label="备注" />
                                <v-file-input color="primary" clearable label="音频文件" show-size accept="audio/mp3,audio/wav,audio/ogg" 
                                    @update:model-value="uploadSentenceAudio($event,index)" />
                                <audio :src="sentence.resource" controls v-if="sentence.resource!=null" />
                                <v-divider />
                                <br>
                            </v-sheet>
                            <v-btn color="primary" @click="addSentenceList">新增</v-btn>
                        </v-expansion-panel-text>
                    </v-expansion-panel>
                </v-expansion-panels>
            </v-sheet>

            <br>
            <v-btn color="primary" class="me-4" @click="save">保存</v-btn>
            <v-btn class="me-4" @click="temp">暂存</v-btn>
            <v-btn class="me-4" @click="clear">清空</v-btn>
            <v-btn class="me-4" @click="loadLocalWordBo">继续</v-btn>
            <v-checkbox v-model="autoClear" label="保存成功后自动清空" />
        </form>
        <v-dialog v-model="showDialog" :scrim="true" persistent width="auto">
            <template v-slot:default="{ isActive }">
                <v-card :title="result.code + ''" v-show="result.code == 0">
                    <v-card-text> {{ result.msg }} </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn text="关闭" @click="isActive.value = false"></v-btn>
                    </v-card-actions>
                </v-card>
                <v-card color="primary" v-show="showLoading">
                    <v-card-text>
                        正在添加单词，请稍后...
                        <v-progress-linear indeterminate color="white" class="mb-0" />
                    </v-card-text>
                </v-card>
            </template>
        </v-dialog>
        <v-snackbar v-model="snackbar">
            {{ snackbarMsg }}
            <!-- <template v-slot:actions>
                <v-btn color="pink" variant="text" @click="snackbar = false">
                    Close
                </v-btn>
            </template> -->
        </v-snackbar>
    </v-container>
</template>

<script>
import { langList } from "@/api/lang.js";
import { labelList } from "@/api/label.js";
import { bookList } from "@/api/book.js";
import { addWord, getWordDetail, updateWord } from "@/api/word.js";
import {searchZh} from '@/api/search'
import { uploadUserSingleFile } from '@/api/uploadUserFile.js'
import { getSnowflakeId } from '@/api/publicApi';

export default {
    name: 'DIYWordView',
    data() {
        return {
            showDialog: false,
            showLoading: true,
            autoClear: false,
            wordBo: {},
            langList: [],
            labelList: [],
            bookList: [],
            translatedMeaningsList: [],
            pronunciationList: [],
            sentenceList: [],
            originalMeanings: {},
            classList: ['n', 'vt', 'vi', 'adj', 'adv', 'pron', 'prep', 'v', 'aux','num'],
            result: {},
            snackbarMsg: '',
            snackbar: false,
            originalMeaningsDefault:{
                explain:'',symbol:undefined
            }
        }
    },
    created() {
        this.getSelectData()
        // console.log('this.$route.params = ',this.$route.params);
        // console.log('this.$route.params.wordId',this.$route.params.wordId)
        if (this.$route.params.wordId != null&&this.$route.params.wordId!='diy')
            this.detail({
                wordId: this.$route.params.wordId,
                bookId: this.$route.params.bookId
            })
        else if(this.$route.params.lang!=null&&this.$route.params.word!=null)
            this.searchWord(this.$route.params.word)
        else
            getSnowflakeId().then(resp=>this.wordBo.wordId=resp.data)
    },
    methods: {
        getSelectData() {
            langList({}).then(resp => {
                this.langList = resp.data
            })
            labelList({}).then(resp => {
                this.labelList = resp.data
            })
            bookList().then(resp => {
                this.bookList = resp.rows
            })
        },
        addtranslatedMeanings() {
            this.translatedMeaningsList.push({
                mean: undefined, remark: undefined, type: undefined
            })
        },
        addPronunciationList() {
            this.pronunciationList.push({
                region: undefined, symbol: undefined, remark: undefined, resource: undefined
            })
        },
        addSentenceList() {
            this.sentenceList.push({
                self: undefined, resource: undefined, mean: undefined, remark: undefined
            })
        },
        buildWord() {
            this.wordBo.originalMeanings = this.getoriginalMeanings()
            this.wordBo.translatedMeanings = this.translatedMeaningsList
            this.wordBo.pronunciation = this.getPronunciationList()
            this.wordBo.sentence = this.getSentenceList()
            // console.log(this.wordBo);
        },
        save() {
            this.buildWord()
            this.showDialog = true
            this.showLoading = true
            this.result={}
            // console.log('this.$route.params.wordId = ',this.$route.params.wordId);
            if (this.$route.params.wordId == null||this.$route.params.wordId=='diy'||this.$route.params.copy=='true') {
                addWord(this.wordBo).then(resp => {
                    this.result = resp
                    this.showLoading = false
                    this.showDialog = false
                    this.snackbar = true
                    if (resp.code == 1) {
                        this.snackbarMsg = '添加成功'
                        if(this.autoClear)this.wordBo={}
                    }else {
                        this.snackbarMsg = '添加失败'
                    }
                })
            }else{
                updateWord(this.wordBo).then(resp => {
                    this.result = resp
                    this.showLoading = false
                    this.showDialog = false
                    this.snackbar = true
                    if (resp.code == 1) {
                        if(this.autoClear)this.wordBo={}
                        this.snackbarMsg = '修改成功'
                    }else {
                        this.snackbarMsg = '添加失败'
                    }
                })
            }

            setTimeout(() => {
                // console.log('this.result ',this.result);
                if (this.result == undefined || this.result.code == undefined) {
                    this.result = {}
                    this.snackbar = true
                    this.showLoading = false
                    this.showDialog = false
                    this.snackbarMsg = '连接超时'
                }
            }, 5000);
        },
        temp() {
            this.buildWord()
            localStorage.setItem('DIYWordBo', JSON.stringify(this.wordBo))
        },
        loadLocalWordBo(){
            this.keep(JSON.parse(localStorage.getItem('DIYWordBo')))
        },
        keep(wordBo) {
            this.wordBo = wordBo
            if(this.$route.params.copy=='true')
                this.wordBo.wordId=null
            if(this.wordBo.pronunciation!=null)
                this.setPronunciationList(this.wordBo.pronunciation)
            if(this.wordBo.sentence)
                this.setSentenceList(this.wordBo.sentence)
            this.translatedMeaningsList = this.wordBo.translatedMeanings
            this.wordBo.originalMeanings.forEach(item => {
                let meanString = ''
                for (let i = 0; i < item.meaning.length; i++) {
                    if (i + 1 == item.meaning.length) meanString += item.meaning[i].explain
                    else meanString += item.meaning[i].explain + '\n'
                }
                if(item.type!=undefined){
                    this.originalMeanings[item.type.replace('.','')] = meanString;
                }else{
                    this.originalMeaningsDefault.explain=meanString
                    this.originalMeaningsDefault.symbol=item.symbol
                }
                //this.originalMeanings[item.type] = meanString
            })
        },
        clear() {
            this.wordBo = {}
            this.originalMeanings = {}
            this.translatedMeaningsList = []
            this.pronunciationList = []
            this.sentenceList = []
        },
        detail(row) {
            getWordDetail(row).then(resp => {
                // console.log(resp.data);
                this.keep(resp.data)
            })
        },
        getoriginalMeanings() {
            let originalMeanings = []
            let clazz = ['noun', 'verb', 'adj', 'adv', 'prep', 'pron', 'aux','num']
            clazz.forEach(clazzItem => {
                if (this.originalMeanings[clazzItem] != null && this.originalMeanings[clazzItem].trim() != '') {
                    let originalMeaningsItem = { type: clazzItem, mean: [],symbol:this.originalMeanings[clazzItem+'Symbol']}
                    let meanSplit = this.originalMeanings[clazzItem].trim().split('\n')
                    meanSplit.forEach(mean => {
                        originalMeaningsItem.meaning.push({
                            explain: mean, sentence: '', audioUrl: ''
                        })
                    })
                    originalMeanings.push(originalMeaningsItem)
                }
            })
            // console.log('originalMeanings = ',originalMeanings)
            if(this.originalMeaningsDefault.explain!=null&&this.originalMeaningsDefault.explain!=''){
                let mean=[]
                if(this.originalMeaningsDefault.explain.search('\n')==-1)mean.push({explain:this.originalMeaningsDefault.explain});
                else {
                    this.originalMeaningsDefault.explain.split('\n').forEach(item=>{
                        if(item!=null&&item!='')mean.push({explain:item})
                    })
                }
                originalMeanings.push({
                    symbol:this.originalMeaningsDefault.symbol,mean:mean
                })
            }
                
            return originalMeanings
        },
        searchWord(word) {
            // this.searchHistory.push(this.searchText)
            // localStorage.setItem('zh_history',JSON.stringify(this.searchHistory))
            searchZh({'word':word}).then(resp=>{
                this.keep(resp.data)
            })
        },
        getPronunciationList() {
            return this.pronunciationList
        },
        setPronunciationList(pronunciation) {
            this.pronunciationList = pronunciation
        },
        getSentenceList() {
            return this.sentenceList
        },
        setSentenceList(sentence) {
            this.sentenceList = sentence
        },
        uploadWordImage(fileList) {            
            if (fileList == null) return
            uploadUserSingleFile(fileList, {'categoryEnum':'image','wordId':this.wordBo.wordId}).then(resp=>{
                if(resp.code==1){
                    this.wordBo.image = resp.data
                }else{
                    this.snackbar = true
                    this.snackbarMsg = '上传失败'
                }
            })
        },
        uploadPronunciationAudio(audioFile,index){
            if(audioFile==null)return
            uploadUserSingleFile(audioFile, {'categoryEnum':'voice','wordId':this.wordBo.wordId}).then(resp=>{
                if(resp.code==1){
                    this.pronunciationList[index].resource = resp.data
                }
            })
        },
        uploadSentenceAudio(audioFile,index){
            if(audioFile==null)return
            uploadUserSingleFile(audioFile, {'categoryEnum':'voice','wordId':this.wordBo.wordId}).then(resp=>{
                if(resp.code==1){
                    this.sentenceList[index].resource = resp.data
                }
            })
        }
    }
}
</script>

<style scoped></style>